package com.example.webdemo.controller;

import com.example.webdemo.util.JsonResult;
import com.example.webdemo.util.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Objects;

@RestController
@RequestMapping("/token")
public class TokenController {

    @Autowired
    private final JwtTokenUtil jwtTokenUtil;

    @Autowired
    public TokenController(JwtTokenUtil jwtTokenUtil) {
        this.jwtTokenUtil = jwtTokenUtil;
    }

    //检测Token是否合法
    public JsonResult<Object> CheckToken(Object token, Object username) {
        try {
            String userclaim = jwtTokenUtil.extractUsername(token.toString());
            if (!Objects.equals(userclaim, username)) {
                return JsonResult.error("Token非法：用户名不匹配");
            }
        }catch (Exception e){
            return JsonResult.error("Token异常: " + e.getMessage());
        }
        if(jwtTokenUtil.isTokenExpired(token.toString())==true){
            return JsonResult.error("Token已过期");
        }
        return JsonResult.success();
    }

}
